import 'package:flutter/material.dart';
import 'package:hm_pda_app/components/top_header.dart';
import 'package:hm_pda_app/config/http_request.dart';
import 'package:hm_pda_app/components/loading_overlay.dart';

class IncomingGoodsInquiry extends StatefulWidget {
  const IncomingGoodsInquiry({super.key});
  @override
  State<StatefulWidget> createState() {
    return IncomingGoodsInquiryState();
  }
}

class IncomingGoodsInquiryState extends State<IncomingGoodsInquiry> {
  final _skuController = TextEditingController();
  final _focusNode = FocusNode();
  // 声明列表数据
  List<ListItem> listData = [];
  SkuInfo? _skuInfo;
  void _queryDataList(BuildContext context) async {
    try {
      if (_skuController.text.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('请输入来货单号'), duration: Duration(seconds: 3)),
        );
        return;
      }
      LoadingOverlay.show(context);
      var response = await HttpUtil.post(
        '/storage/incomingGoods/list',
        data: {
          'incomingGoodsNo': _skuController.text,
          'pageNum': 1,
          'pageSize': 100,
        },
      );

      setState(() {
        listData.clear();
        if (response.code == 200 && response.data != null) {
          if (response.data is Map<String, dynamic>) {
            final dataMap = response.data as Map<String, dynamic>;
            if (dataMap['rows'] is List) {
              for (var item in dataMap['rows']) {
                listData.add(ListItem.fromJson(item));
              }
              if (dataMap['rows'].isNotEmpty) {
                _skuInfo = SkuInfo.fromJson(dataMap['rows'][0]);
              }
            }
          }
          print('listData--$listData');
        } else {
          // 处理错误情况
          print('Error: ${response.message}');
        }
      });
    } catch (e) {
      print(e);
    } finally {
      LoadingOverlay.hide();
    }
  }

  @override
  void initState() {
    super.initState();
    _focusNode.requestFocus();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //appBar: AppBar(title: const Text("移库")),
      appBar: const TopHeader(title: '来货查询'),
      endDrawer: const CustomDrawer(),
      resizeToAvoidBottomInset: false,
      body: SingleChildScrollView(
        padding: EdgeInsets.all(1),
        child: Column(
          children: [
            Row(
              children: [
                Expanded(flex: 2, child: Text('来货单号')),
                Expanded(
                  flex: 6,
                  child: TextField(
                    controller: _skuController,
                    focusNode: _focusNode,
                    decoration: InputDecoration(
                      hintText: '请输入单号',
                      border: OutlineInputBorder(),
                    ),
                    onSubmitted: (value) {
                      _queryDataList(context);
                    },
                  ),
                ),
                // Expanded(
                //   flex: 2,
                //   child: Padding(
                //     padding: EdgeInsets.only(left: 8.0),
                //     child: ElevatedButton(
                //       onPressed: () {
                //         _queryDataList(context);
                //       },
                //       style: ElevatedButton.styleFrom(
                //         backgroundColor: Colors.blue,
                //         foregroundColor: Colors.white,
                //       ),
                //       child: Text('查询'),
                //     ),
                //   ),
                // ),
              ],
            ),
            const Divider(
              height: 2, // 容器总高度2像素
              thickness: 1, // 分割线厚度5像素
              indent: 0, // 左侧缩进20像素
              endIndent: 0, // 右侧无缩进
              color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
            ),
            // 显示SKU信息
            if (_skuInfo != null) ...[
              Card(
                margin: EdgeInsets.all(2),
                child: Padding(
                  padding: EdgeInsets.all(0.5),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          Expanded(
                            child: Text(
                              '供应商代码:${_skuInfo!.supplierCode ?? ''}',
                            ),
                          ),
                          Expanded(
                            child: Text(
                              '供应商名称:${_skuInfo!.supplierName ?? ''}',
                            ),
                          ),
                        ],
                      ),
                      Row(
                        children: [
                          Expanded(
                            child: Text('采购员:${_skuInfo!.purchaseName ?? ''}'),
                          ),
                          Expanded(
                            child: Text(
                              '联系人:${_skuInfo!.incomingGoodsUserName ?? ''}',
                            ),
                          ),
                        ],
                      ),
                      Row(
                        children: [
                          Expanded(
                            child: Text('车牌号:${_skuInfo!.licencePlate ?? ''}'),
                          ),
                          Expanded(
                            child: Text(
                              '物流单号:${_skuInfo!.logisticsOrderNo ?? ''}',
                            ),
                          ),
                        ],
                      ),
                      Row(
                        children: [
                          Expanded(
                            child: Text(
                              '来货类型:${_skuInfo!.businessTypeName ?? ''}',
                            ),
                          ),
                          Expanded(
                            child: Text(
                              '来货箱数:${_skuInfo!.actualIncomingGoodsNum ?? ''}',
                            ),
                          ),
                        ],
                      ),
                      if (_skuInfo!.remark != null &&
                          _skuInfo!.remark!.isNotEmpty)
                        Row(
                          children: [
                            Expanded(child: Text('备注:${_skuInfo!.remark}')),
                          ],
                        ),
                    ],
                  ),
                ),
              ),
              const Divider(
                height: 2,
                thickness: 1,
                indent: 0,
                endIndent: 0,
                color: Color.fromARGB(255, 109, 108, 108),
              ),
            ],
            // 显示列表数据
            if (listData.isNotEmpty) _buildList(),
          ],
        ),
      ),
      bottomNavigationBar: DecoratedBox(
        decoration: BoxDecoration(color: const Color.fromARGB(255, 77, 76, 76)),
        child: SizedBox(
          width: double.infinity,
          height: 50,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Row(
              children: [
                Expanded(
                  child: SizedBox(
                    height: 40,
                    child: OutlinedButton(
                      onPressed: () {
                        // 清除表单和数据
                        setState(() {
                          _skuController.clear();
                          listData.clear();
                          _skuInfo = null;
                        });
                        _focusNode.requestFocus();
                      },
                      style: OutlinedButton.styleFrom(
                        foregroundColor: Colors.white,
                        backgroundColor: Colors.grey[600],
                        side: BorderSide.none,
                        textStyle: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 1,
                      ),
                      child: const Text('清除'),
                    ),
                  ),
                ),
                const SizedBox(width: 12),

                Expanded(
                  child: SizedBox(
                    height: 40,
                    child: ElevatedButton(
                      onPressed: () {
                        _queryDataList(context);
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue[600],
                        foregroundColor: Colors.white,
                        textStyle: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 3,
                        // shadowColor: Colors.blue.withOpacity(0.3),
                      ),
                      child: const Text('查询'),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 列表数据展示
  Widget _buildList() {
    return ListView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: listData.length,
      itemBuilder: (context, index) {
        final item = listData[index];
        return Card(
          margin: EdgeInsets.all(2),
          child: Padding(
            padding: EdgeInsets.all(0.5),

            child: Column(
              children: [
                Row(
                  children: [
                    Expanded(child: Text('SKU:${item.skuCode}')),
                    Expanded(child: Text('SPU:')),
                  ],
                ),
                Row(
                  children: [
                    Expanded(child: Text('规格:')),
                    Expanded(child: Text('产品名称:')),
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                      child: Text('预计来货数:${item.expectIncomingGoodsNum}'),
                    ),
                    Expanded(child: Text('采购单号:')),
                  ],
                ),
                Row(children: [Expanded(child: Text('备注:${item.remark}'))]),
              ],
            ),
          ),
        );
      },
    );
  }
}

class ListItem {
  final String? supplierCode;
  final String? supplierName;
  final String? purchaseName;
  final String? incomingGoodsUserName;
  final String? licencePlate;
  final String? logisticsOrderNo;
  final String? businessTypeName;
  final String? remark;
  final String? actualIncomingGoodsNum;
  final String? skuCode;
  final String? expectIncomingGoodsNum;

  ListItem({
    this.supplierCode,
    this.supplierName,
    this.purchaseName,
    this.incomingGoodsUserName,
    this.licencePlate,
    this.logisticsOrderNo,
    this.businessTypeName,
    this.remark,
    this.actualIncomingGoodsNum,
    this.skuCode,
    this.expectIncomingGoodsNum,
  });
  factory ListItem.fromJson(Map<String, dynamic> json) {
    return ListItem(
      supplierCode: json['supplierCode']?.toString() ?? '',
      supplierName: json['supplierName']?.toString() ?? '',
      purchaseName: json['purchaseName']?.toString() ?? '',
      incomingGoodsUserName: json['incomingGoodsUserName']?.toString() ?? '',
      licencePlate: json['licencePlate']?.toString() ?? '',
      logisticsOrderNo: json['logisticsOrderNo']?.toString() ?? '',
      businessTypeName: json['businessTypeName']?.toString() ?? '',
      remark: json['remark']?.toString() ?? '',
      actualIncomingGoodsNum: json['actualIncomingGoodsNum']?.toString() ?? '',
      skuCode: json['skuCode']?.toString() ?? '',
      expectIncomingGoodsNum: json['expectIncomingGoodsNum']?.toString() ?? '',
    );
  }
}

// sku信息
class SkuInfo {
  final String? supplierCode;
  final String? supplierName;
  final String? purchaseName;
  final String? incomingGoodsUserName;
  final String? licencePlate;
  final String? logisticsOrderNo;
  final String? businessTypeName;
  final String? remark;
  final String? actualIncomingGoodsNum;

  SkuInfo({
    this.supplierCode,
    this.supplierName,
    this.purchaseName,
    this.incomingGoodsUserName,
    this.licencePlate,
    this.logisticsOrderNo,
    this.businessTypeName,
    this.remark,
    this.actualIncomingGoodsNum,
  });
  factory SkuInfo.fromJson(Map<String, dynamic> json) {
    return SkuInfo(
      supplierCode: json['supplierCode']?.toString() ?? '',
      supplierName: json['supplierName']?.toString() ?? '',
      purchaseName: json['purchaseName']?.toString() ?? '',
      incomingGoodsUserName: json['incomingGoodsUserName']?.toString() ?? '',
      licencePlate: json['licencePlate']?.toString() ?? '',
      logisticsOrderNo: json['logisticsOrderNo']?.toString() ?? '',
      businessTypeName: json['businessTypeName']?.toString() ?? '',
      remark: json['remark']?.toString() ?? '',
      actualIncomingGoodsNum: json['actualIncomingGoodsNum']?.toString() ?? '',
    );
  }
}
